<template>
  <div
    v-loading.fullscreen.lock="loading"
    class="app-container calendar-list-container"
    element-loading-text="玩命加载中"
    element-loading-background="rgba(0, 0, 0, 0.2)"
  >
    <div style="display:inline">
      <el-upload
        ref="upload"
        style="display:inline"
        :headers="headers"
        :action="base_api+url"
        :accept="accept"
        :show-file-list="false"
        :auto-upload="true"
        :limit="1"
        :customparama="datas"
        :multiple="false"
        :http-request="uploadFile"
      >
        <el-button slot="trigger" type="primary">
          <slot />
        </el-button>
      </el-upload>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import axios from 'axios'
export default {
  props: {
    url: {
      type: String,
      default: ''
    },
    accept: {
      type: String,
      default: '.xlsx'
    },
    isErrorDown: {
      type: Boolean,
      default: true
    },
    customparama: {
      type: FormData,
      default: undefined
    }
  },
  data() {
    return {
      base_api: process.env.VUE_APP_BASE_API,
      endResult: [],
      datas: undefined,
      loading: false
    }
  },
  computed: {
    imageUrl() {
      return this.value
    },
    headers() {
      return {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  methods: {
    uploadFile(file) {
      this.loading = true
      var data = new FormData()
      const fileUps = file.file
      if (this.customparama !== undefined) {
        data = this.customparama
      }
      data.append('file', fileUps)
      axios({
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'Bearer ' + getToken()
        },
        timeout: 1800000,
        responseType: this.isErrorDown ? 'blob' : '',
        url: this.base_api + this.url,
        data: data,
        method: 'post'
      }).then(
        (response) => {
          this.$refs.upload.clearFiles()
          if (this.isErrorDown) {
            if (response.data.type === 'text/xml') {
              Message({
                message: '上传成功',
                type: 'success',
                duration: 5 * 1000
              })
              this.$emit('success')
            } else if (response.data.type === 'application/json') {
              var self = this
              const reader = new FileReader()
              // eslint-disable-next-line no-unused-vars
              reader.onload = function() {
                this.endResult = JSON.parse(reader.result)
                this.customparama = undefined
                const { message, code, data } = JSON.parse(reader.result)

                if (code !== 0) {
                  Message({
                    message: message,
                    type: 'error',
                    duration: 5 * 1000
                  })
                } else {
                  self.$emit('importSuccess', data)
                }
              }
              reader.readAsText(response.data)
              this.$nextTick(() => {
                this.$emit('success')
              })
            } else if (response.data.type === 'filetype') {
              Message({
                message: "上传文件格式与模板不符",
                type: 'error',
                duration: 5 * 1000
              })
            } else {
              Message({
                message: '上传失败',
                type: 'error',
                duration: 5 * 1000
              })
              this.downloadUrl(response)
            }
          } else {
            if (response.data.code === 0 || response.data.code === '0') {
              Message({
                message: '上传成功',
                type: 'success',
                duration: 5 * 1000
              })
              this.$emit('success')
            } else {
              Message({
                message: response.data.message,
                type: 'error',
                duration: 5 * 1000
              })
            }
          }
        },
        () => {
          this.$refs.upload.clearFiles()
          Message({
            message: '上传失败',
            type: 'error',
            duration: 5 * 1000
          })
        }
      ).finally(res => {
        this.loading = false
      })
    },
    downloadUrl(res) {
      const blob = new Blob([res.data], { type: res.data.type })
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = decodeURI(
        res.headers['content-disposition'].replace('attachment;filename=', '')
      )
      document.body.appendChild(downloadElement)
      downloadElement.click()
      document.body.removeChild(downloadElement)
      window.URL.revokeObjectURL(href)
    }

  }
}
</script>

<style scoped>
.excel-upload-input {
  display: none;
  z-index: -9999;
}
</style>
